package io.github.stary1993.kite.admin.config;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import io.github.stary1993.kite.admin.entity.SysRole;
import io.github.stary1993.kite.admin.service.SysUserService;
import io.github.stary1993.kite.admin.vo.UserVO;
import io.github.stary1993.kite.core.constant.CommonConstants;
import io.github.stary1993.kite.core.constant.SecurityConstants;
import io.github.stary1993.kite.security.core.SecurityUser;
import io.github.stary1993.kite.security.support.SecurityUserDetailsService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 用户密码登录
 *
 * @author stary1993
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class UserPasswordUserDetailsService implements SecurityUserDetailsService {


    private final SysUserService sysUserService;

    /**
     * 用户名密码登录
     *
     * @param username 用户名
     * @return
     */
    @Override
    @SneakyThrows
    public UserDetails loadUserByUsername(String username) {
        UserVO userVO = sysUserService.detailsByUsername(username);
        List<SysRole> roleList = userVO.getRoleList();
        List<String> permissions = new ArrayList<>();
        Set<String> dbAuthsSet = new HashSet<>();

        if (ArrayUtil.isNotEmpty(userVO.getRoleList())) {
            // 获取角色
            roleList.forEach(role -> dbAuthsSet.add(SecurityConstants.ROLE + role.getRoleCode()));
            // 获取资源
            dbAuthsSet.addAll(permissions);
        }

        Collection<GrantedAuthority> authorities = AuthorityUtils
                .createAuthorityList(dbAuthsSet.toArray(new String[0]));
        return new SecurityUser(userVO.getUserId(),
                userVO.getUsername(),
                SecurityConstants.BCRYPT + userVO.getPassword(),
                userVO.getPhone(),
                true,
                true,
                true,
                StrUtil.equals(userVO.getLockFlag(), CommonConstants.STATUS_NORMAL),
                authorities);
    }

}
